from django.shortcuts import render
from .models import ContentCategory
from meiduo_mall.utils.meiduo_category import get_categories
import os
from django.conf import settings


def generate_static_index_html():
    # 1.生成html字符串
    # 1.1.查询频道分类信息
    categories = get_categories()
    # 1.2.查询广告信息
    contents = ContentCategory.objects.all()
    contents_dict = {}
    for content in contents:
        contents_dict[content.key] = content.content_set.filter(status=True).order_by('sequence')
    context = {
        'categories': categories,
        'contents': contents_dict
    }
    # 1.3获取html字符串
    response = render(None, 'index.html', context)
    html_str = response.content.decode()

    # 2.将字符串写到文件中，表示在当前项目目录下添加的路径
    file_path = os.path.join(settings.BASE_DIR, 'static/index.html')
    with open(file_path, 'w') as f1:
        f1.write(html_str)
